import React, { useEffect, useState } from 'react';
import { ICompany, IFile } from '@/ts/core';
import { useEffectOnce } from 'react-use';
import orgCtrl from '@/ts/controller';
import {
  Collapse,
  Empty,
  message,
  Spin,
  Button,
  Space,
  Avatar,
  Select,
} from 'antd';
import EntityIcon from '@/components/Common/GlobalComps/entityIcon';
import ListMode from '@/components/Directory/views/listMode';
import './index.less';
import { IAssignTask } from '@/ts/core/work/assign';
import { operatesToMenus } from '@/executor/fileOperate';
import { Moment } from 'moment';

const Panel = Collapse.Panel;

interface IProps {
  height?: string;
  openTask: (task: IAssignTask) => void;
  targetMetadataId: string;
}

export default function TaskViewer(props: IProps) {
  const [spaces, setSpaces] = useState<ICompany[]>([]);
  const [activeKey, setActiveKey] = useState('');
  const [tasks, setTasks] = useState<IAssignTask[]>([]);
  const [selectedTask, setSelectedTask] = useState<IAssignTask>();
  const [loading, setLoading] = useState(false);
  const [taskType, setTaskType] = useState<
    'month' | 'year' | 'all' | 'Inventory' | 'PropertyInventory' | 'RevitalizeReports'
  >('all');
  const [taskStatusFilter, setTaskStatusFilter] = useState<string>('');
  const [selectedDate, setSelectedDate] = useState<Moment | null>(null);

  useEffectOnce(() => {
    loadCompanys();
  });

  useEffect(() => {
    if (spaces.length > 0 && activeKey) {
      refreshTasks(true);
    }
  }, [taskStatusFilter, taskType, selectedDate, spaces, activeKey]);


  async function loadCompanys() {
    const companys = orgCtrl.user.companys;
    const filteredCompanys = companys.filter(
      (company) => company.metadata.id === props.targetMetadataId,
    );

    if (filteredCompanys.length > 0) {
      setSpaces(filteredCompanys);
      setActiveKey(filteredCompanys[0].id);
    } else {
      setSpaces([]);
      message.warning('未找到匹配的单位数据！');
    }
  }

  async function loadTasks(company: ICompany, type: 'month' | 'year', reload = false) {
    const tasks =
      type === 'month'
        ? await company.loadPaddingTasks(reload)
        : await company.loadPaddingYearTasks(reload);
    return tasks.sort((a, b) => {
      return (
        new Date(b.metadata.updateTime).getTime() -
        new Date(a.metadata.updateTime).getTime()
      );
    });
  }

  async function refreshTasks(reload = false, overrideType) {
    setLoading(true);
    setTasks([]);
    setSelectedTask(undefined);

    const company = spaces.find((s) => s.id === activeKey);
    if (!company) return;

    let currentType = overrideType || taskType;

    let loadedTasks = [];
    switch (currentType) {
      case 'all':
        loadedTasks = await company.loadAssignTasks(reload);
        break;
      case 'month':
        loadedTasks = await loadTasks(company, 'month', reload);
        break;
      case 'year':
        loadedTasks = await loadTasks(company, 'year', reload);
        break;
      case 'Inventory':
        loadedTasks = await company.loadInventoryTasks(reload); // 新增方法
        break;
      case 'PropertyInventory':
        loadedTasks = await company.loadPropertyInventoryTasks(reload); // 新增方法
        break;
      case 'RevitalizeReports':
        loadedTasks = await company.loadRevitalizeReportsTasks(reload); // 新增方法
        break;
      default:
        loadedTasks = [];
    }

    if (taskStatusFilter) {
      loadedTasks = loadedTasks.filter((task) => task.taskStatus === taskStatusFilter);
    }

    if (selectedDate) {
      const formattedDate = selectedDate.format(
        currentType === 'month' ? 'YYYY-MM' : 'YYYY',
      );
      loadedTasks = loadedTasks.filter((task) => task.period === formattedDate);
    }

    setTasks(loadedTasks);
    setLoading(false);
  }

  async function openTask(entity: IAssignTask) {
    setSelectedTask(entity);
    props.openTask(entity);
  }

  const contextMenu = (file?: IFile) => ({
    items: operatesToMenus(
      [
        {
          sort: 1,
          cmd: 'cancelReceive',
          label: '取消接收',
          iconType: 'restore',
        },
      ],
      file as IAssignTask,
    ),
    onClick: async ({ key }: { key: string }) => {
      if (key === 'cancelReceive' && file) {
        const ret = await (file as IAssignTask).cancelReceive();
        if (ret) {
          message.success('取消接收任务成功');
          refreshTasks();
        }
      }
    },
  });

  const handleChangeTaskType = async (
    type:
      | 'month'
      | 'year'
      | 'all'
      | 'Inventory'
      | 'PropertyInventory'
      | 'RevitalizeReports',
  ) => {
    setTaskType(type);
    await refreshTasks(true, type);
  };


  const handleTaskStatusFilter = (status: string) => {
    setTaskStatusFilter(status);
  };

  const handleDateChange = (date: Moment | null) => {
    setSelectedDate(date);
  };
  const taskStatusOptions = [
    { label: '全部', value: '' },
    { label: '已接收', value: 'received' },
    { label: '已完结', value: 'finished' },
    { label: '已上报', value: 'submitted' },
    { label: '已退回', value: 'rejected' },
  ];
  return (
    <div className="task-viewer" style={{ height: props.height || '100%' }}>
      <div className="task-status-filter" style={{display: 'flex', justifyContent: 'flex-end' }}>
        <Space>
          <Select
            style={{ width: 90 }}
            value={taskStatusFilter}
            onChange={(value) => handleTaskStatusFilter(value)}
            options={taskStatusOptions}
            placeholder="选择状态"
          />
          <Button loading={loading} onClick={() => refreshTasks(true)}>
            重载任务
          </Button>
        </Space>
      </div>

      <div className="directory-viewer group-collapse">
        {loading && <Spin spinning className="loading-spin" />}
        <Collapse
          accordion
          activeKey={activeKey}
          onChange={(key) => setActiveKey(key as string)}>
          {spaces.map((g) => (
            <Panel header={<EntityIcon entity={g.metadata} showName />} key={g.id}>
              <Collapse
                accordion
                onChange={(type) =>
                  handleChangeTaskType(
                    type as
                      | 'all'
                      | 'month'
                      | 'year'
                      | 'Inventory'
                      | 'PropertyInventory'
                      | 'RevitalizeReports',
                  )
                }>
                <Panel
                  header={
                    <div style={{ display: 'flex', alignItems: 'center', height: 50 }}>
                      <Avatar
                        src="public/img/assign/all.png"
                        shape="square"
                        size="large"
                        style={{ marginRight: 18 }}
                      />
                      全部任务
                    </div>
                  }
                  key="all">
                  {taskType === 'all' && tasks.length > 0 ? (
                    <ListMode
                      selectFiles={[]}
                      focusFile={selectedTask}
                      isMenu
                      content={tasks}
                      directory={g.directory}
                      fileOpen={(f, dblclick) => !dblclick && openTask(f as IAssignTask)}
                      contextMenu={(f) => (f ? contextMenu(f as IAssignTask) : {})}
                    />
                  ) : (
                    <Empty />
                  )}
                </Panel>
                <Panel
                  header={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <Avatar
                        src="public/img/assign/month.png"
                        shape="square"
                        size="large"
                        style={{ marginRight: 18 }}
                      />
                      资产月报
                    </div>
                  }
                  key="month">
                  {taskType === 'month' && tasks.length > 0 ? (
                    <ListMode
                      selectFiles={[]}
                      focusFile={selectedTask}
                      isMenu
                      content={tasks}
                      directory={g.directory}
                      fileOpen={(f, dblclick) => !dblclick && openTask(f as IAssignTask)}
                      contextMenu={(f) => (f ? contextMenu(f as IAssignTask) : {})}
                    />
                  ) : (
                    <Empty />
                  )}
                </Panel>
                <Panel
                  header={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <Avatar
                        src="public/img/assign/year.png"
                        shape="square"
                        size="large"
                        style={{ marginRight: 18 }}
                      />
                      资产年报
                    </div>
                  }
                  key="year">
                  {taskType === 'year' && tasks.length > 0 ? (
                    <ListMode
                      selectFiles={[]}
                      focusFile={selectedTask}
                      isMenu
                      content={tasks}
                      directory={g.directory}
                      fileOpen={(f, dblclick) => !dblclick && openTask(f as IAssignTask)}
                      contextMenu={(f) => (f ? contextMenu(f as IAssignTask) : {})}
                    />
                  ) : (
                    <Empty />
                  )}
                </Panel>
                <Panel
                  header={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <Avatar
                        src="public/img/assign/Inventory.png"
                        shape="square"
                        size="large"
                        style={{ marginRight: 18 }}
                      />
                      清查盘点
                    </div>
                  }
                  key="Inventory">
                  {taskType === 'Inventory' && tasks.length > 0 ? (
                    <ListMode
                      selectFiles={[]}
                      focusFile={selectedTask}
                      isMenu
                      content={tasks}
                      directory={g.directory}
                      fileOpen={(f, dblclick) => !dblclick && openTask(f as IAssignTask)}
                      contextMenu={(f) => (f ? contextMenu(f as IAssignTask) : {})}
                    />
                  ) : (
                    <Empty />
                  )}
                </Panel>
                <Panel
                  header={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <Avatar
                        src="public/img/assign/PropertyInventory.png"
                        shape="square"
                        size="large"
                        style={{ marginRight: 18 }}
                      />
                      房产清查
                    </div>
                  }
                  key="PropertyInventory">
                  {taskType === 'PropertyInventory' && tasks.length > 0 ? (
                    <ListMode
                      selectFiles={[]}
                      focusFile={selectedTask}
                      isMenu
                      content={tasks}
                      directory={g.directory}
                      fileOpen={(f, dblclick) => !dblclick && openTask(f as IAssignTask)}
                      contextMenu={(f) => (f ? contextMenu(f as IAssignTask) : {})}
                    />
                  ) : (
                    <Empty />
                  )}
                </Panel>
                <Panel
                  header={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <Avatar
                        src="public/img/assign/RevitalizeReports.png"
                        shape="square"
                        size="large"
                        style={{ marginRight: 18 }}
                      />
                      盘活报表
                    </div>
                  }
                  key="RevitalizeReports">
                  {taskType === 'RevitalizeReports' && tasks.length > 0 ? (
                    <ListMode
                      selectFiles={[]}
                      focusFile={selectedTask}
                      isMenu
                      content={tasks}
                      directory={g.directory}
                      fileOpen={(f, dblclick) => !dblclick && openTask(f as IAssignTask)}
                      contextMenu={(f) => (f ? contextMenu(f as IAssignTask) : {})}
                    />
                  ) : (
                    <Empty />
                  )}
                </Panel>
              </Collapse>
            </Panel>
          ))}
        </Collapse>
      </div>
    </div>
  );
}
